package dhm.com.hpx.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.qiniu.pili.droid.shortvideo.PLShortVideoTranscoder;
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener;
import com.zhy.http.okhttp.OkHttpUtils;

import static com.qiniu.pili.droid.shortvideo.PLErrorCode.ERROR_LOW_MEMORY;
import static com.qiniu.pili.droid.shortvideo.PLErrorCode.ERROR_NO_VIDEO_TRACK;
import static com.qiniu.pili.droid.shortvideo.PLErrorCode.ERROR_SRC_DST_SAME_FILE_PATH;
import static java.util.regex.Pattern.compile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dhm.com.hpx.R;
import dhm.com.hpx.adapter.AddextensionAdapter;
import dhm.com.hpx.base.BaseActivity;
import dhm.com.hpx.base.netWork.Constant;
import dhm.com.hpx.base.netWork.LoginContract;
import dhm.com.hpx.entity.AddVideoBean;
import dhm.com.hpx.entity.AddextensionBean;
import dhm.com.hpx.entity.Bean;
import dhm.com.hpx.utils.BitmapUtil;
import dhm.com.hpx.utils.ExtensionCallback;
import dhm.com.hpx.utils.SpUtils;
import dhm.com.hpx.utils.TakePhotoUtil;
import dhm.com.hpx.utils.UriUtils;
import dhm.com.hpx.utils.VideoCallback;
import dhm.com.hpx.view.FullWindowVideoView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AddextensionActivity extends BaseActivity implements LoginContract.IView {

    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.video_view)
    FullWindowVideoView videoView;
    @BindView(R.id.img_thumb)
    ImageView imgThumb;
    @BindView(R.id.img_play)
    ImageView imgPlay;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.love)
    TextView love;
    @BindView(R.id.check_video)
    LinearLayout check_video;
    @BindView(R.id.check_article)
    LinearLayout check_article;
    @BindView(R.id.edit_wechat)
    EditText editWechat;
    @BindView(R.id.edit_title)
    EditText edit_title;
    @BindView(R.id.edit_desc)
    EditText edit_desc;
    @BindView(R.id.edit_link)
    EditText edit_link;
    @BindView(R.id.wechat_card)
    SimpleDraweeView wechatCard;
    @BindView(R.id.image)
    SimpleDraweeView image;
    @BindView(R.id.videoimage)
    SimpleDraweeView videoimage;
    @BindView(R.id.video_rela)
    RelativeLayout video_rela;
    @BindView(R.id.recycle)
    RecyclerView recycle;
    AddextensionAdapter adapter;
    private List<String> sexlist = new ArrayList<>();
    private String uid;
    List<AddextensionBean> list = new ArrayList<>();

    boolean iswechat_card = true;
    private String type;

    List<String> platformLiat = new ArrayList();
    private String link;
    private Uri videouri;

    @Override
    protected int getLayout() {
        return R.layout.activity_addextension;
    }

    int position;

    private OptionsPickerView pvOptions;

    @Override
    protected void initView() {
        ButterKnife.bind(this);

        okHttpClient = new OkHttpClient.Builder()
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS)
                .build();

        type = getIntent().getStringExtra("type");
        sexlist.clear();
        sexlist.add("拍照");
        sexlist.add("相册");
        platformLiat.clear();



        platformLiat.add("抖音");
        platformLiat.add("快手");
        platformLiat.add("淘宝");
        platformLiat.add("阿里");
        platformLiat.add("咸鱼");
        platformLiat.add("京东");
        platformLiat.add("飞猪");
        platformLiat.add("火山 视频（极速版）");
        platformLiat.add("拼多多");
        platformLiat.add("饿了么");
        platformLiat.add("阿里巴巴");
        platformLiat.add("美团");

        switch (type) {
            case "1":
                title.setText("定向文章");
                check_article.setVisibility(View.VISIBLE);
                check_video.setVisibility(View.GONE);
                break;
            case "2":
                title.setText("定向视频");
                check_article.setVisibility(View.GONE);
                check_video.setVisibility(View.VISIBLE);
                break;
            default:
        }

        uid = SpUtils.getString(this, "uid");
        listAdd();

    }

    /**
     * 获取所有满足正则表达式的字符串
     *
     * @param str   需要被获取的字符串
     * @param regex 正则表达式
     * @return 所有满足正则表达式的字符串
     */
    private String getAllSatisfyStr(String str, String regex) {
        if (str == null || str.isEmpty()) {
            return null;
        }
        str = "2👈！DYfTXdfksOW哈 https://m.tb.cn/h.4qNeayG?sm=6d58eb  植护无芯卷纸大卷整箱卫生纸巾批发家用实惠装厕所草纸手纸卷筒纸";
        String allSatisfyStr = "";
        if (regex == null || regex.isEmpty()) {
            allSatisfyStr = str;
            return allSatisfyStr;
        }

        int plength = 0;
        for (int i = 0; i < str.length(); i++) {
            String i1 = str.substring(i, i + 1);
            allSatisfyStr = allSatisfyStr + i1;
            int length = allSatisfyStr.length();
            if (plength == length) {
                allSatisfyStr = allSatisfyStr.substring(0, length);
            } else {
                plength = allSatisfyStr.length();
            }

        }

        return allSatisfyStr;
    }

    private void listAdd() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recycle.setLayoutManager(manager);
        adapter = new AddextensionAdapter(this);
        recycle.setAdapter(adapter);
        adapter.onCommandClick(new AddextensionAdapter.onCommandClick() {
            @Override
            public void item(int posttion, String value) {
//                String allSatisfyStr = getAllSatisfyStr(value, Constant.kouling);
//                value = value.replace("/\\uD83C[\\uDF00-\\uDFFF]|\\uD83D[\\uDC00-\\uDE4F]/g", "");
                list.get(posttion).setCommand(value);
            }
        });
        adapter.onTitleClick(new AddextensionAdapter.OnPlatformClick() {
            @Override
            public void item(final int posttion) {
                //选择地址
                pvOptions = new OptionsPickerBuilder(AddextensionActivity.this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        list.get(posttion).setPlatform(options1 + 1);
                        adapter.setList(list);
                    }
                }).build();
                //三级选择器
                pvOptions.setPicker(platformLiat);
                pvOptions.show();
            }
        });

        AddextensionBean bean = new AddextensionBean();
        list.add(bean);
        adapter.setList(list);
    }

    @Override
    protected void initData() {

    }


    /**
     * 显示进度框
     */
    private void showProgressDialog() {
        if (progDialog == null) {
            progDialog = new ProgressDialog(this);
        }
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(false);
        progDialog.setMessage("正在上传...");
        progDialog.show();
    }

    /**
     * 隐藏进度框
     */
    private void dissmissProgressDialog() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }

    private final int REQUEST_EXTERNAL_STORAGE = 1;
    private String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private ProgressDialog progDialog = null;// 搜索时进度条
    private Pattern httpPattern;

    @OnClick({R.id.back, R.id.wechat_card, R.id.addmore, R.id.commit, R.id.image, R.id.videoimage, R.id.video_change})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.videoimage:
                if (ContextCompat.checkSelfPermission(AddextensionActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//            LogUtil.d("downApkTag", "Home requestPermissions");
                    ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
                } else {
                    selectVideo();
                }
                break;
            case R.id.video_change:
                selectVideo();
                break;
            case R.id.image:
                iswechat_card = false;
                //选择地址
                pvOptions = new OptionsPickerBuilder(AddextensionActivity.this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        if (options1 == 0) {
                            //拍照
                            takePhotoClick();

                        } else {
                            //相册
                            choose_photo_layout_click();

                        }
                    }
                }).build();
                //三级选择器
                pvOptions.setPicker(sexlist);
                pvOptions.show();
                break;
            case R.id.wechat_card:
                iswechat_card = true;
                //选择地址
                pvOptions = new OptionsPickerBuilder(AddextensionActivity.this, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        if (options1 == 0) {
                            //拍照
                            takePhotoClick();

                        } else {
                            //相册
                            choose_photo_layout_click();
                        }
                    }
                }).build();
                //三级选择器
                pvOptions.setPicker(sexlist);
                pvOptions.show();
                break;
            case R.id.addmore:
                if (list.size() == 5) {
                    Toast.makeText(this, "最多能添加5个呦", Toast.LENGTH_SHORT).show();
                    return;
                }
                listAdd();
                break;
            case R.id.commit:
                String mobile = editPhone.getText().toString();
                String wechat = editWechat.getText().toString();
                String title = edit_title.getText().toString();
                String desc = edit_desc.getText().toString();
                if (type.equals("1")) {
                    link = edit_link.getText().toString();

//初始化正则"
//                    httpPattern = compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$");
                    httpPattern = compile("^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$");
//开始判断了
                    if (!httpPattern.matcher(link).matches()) {
//这不是一个网址链接
                        Toast.makeText(this, "请填写正确的网址链接", Toast.LENGTH_SHORT).show();
                        return;
                    }

                }
                boolean check = true;
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getPlatform() == 0 || list.get(i).getCommand() == null || list.get(i).getCommand().equals("")) {
                        i = list.size();
                        check = false;
                    }
                }
                if (link == null || link.equals("") || title == null || title.equals("") || cover_pic == null || cover_pic.equals("") || !check) {
                    Toast.makeText(this, "请检查数据", Toast.LENGTH_SHORT).show();
                    return;
                }
                String extension_data = new Gson().toJson(list);

                showProgressDialog();
                OkHttpUtils.post().url(Constant.PATH + Constant.extensionadd)
                        .addParams("uid", uid)
                        .addParams("type", type)
                        .addParams("mobile", mobile)
                        .addParams("wechat", wechat)
                        .addParams("title", title)
                        .addParams("wechat_card", wechat_card)
                        .addParams("desc", desc)
                        .addParams("link", link)
                        .addParams("extension_data", extension_data)
                        .addFile("cover_pic", cover_pic, new File(bitmapToString(BitmapUtil.getimage(cover_pic))))
                        .addParams("token", Constant.TOKEN)
                        .build().execute(new ExtensionCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        dissmissProgressDialog();
                        Toast.makeText(AddextensionActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Bean response, int id) {
                        dissmissProgressDialog();
                        Toast.makeText(AddextensionActivity.this, response.getMessage(), Toast.LENGTH_SHORT).show();
                        if (response != null && response.getCode() == 1) {
                            finish();
                        }
                    }
                });

                break;
            default:
        }
    }

    String wechat_card = "";

    private void uploadImage(final String url) {


        OkHttpUtils.post().url(Constant.PATH + Constant.add_pic)
                .addParams("token", Constant.TOKEN)
                .addFile("wechat_card", url, new File(bitmapToString(BitmapUtil.getimage(url))))
                .build().execute(new VideoCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(AddVideoBean response, int id) {
                if (response.getCode() == 1) {
                    wechat_card = response.getData();
                }

            }
        });

    }


    @Override
    public void requesta(Object data) {

    }

    @Override
    public void fail(String error) {

    }

    private boolean isCompressing;
    private static final int TAKE_PICTURE = 0;
    private static final int IMAGE = 1;
    private static final int REQUEST_CODE_ASK_PERMISSIONS = 2;

    /**
     * 拍照
     */
    void takePhotoClick() {
        if (Build.VERSION.SDK_INT >= 23) {
            requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_ASK_PERMISSIONS);
        } else {
            startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), TAKE_PICTURE);
        }
    }

    /**
     * 选取相册图片
     */
    void choose_photo_layout_click() {
        //调用相册
        Intent intent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, IMAGE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), TAKE_PICTURE);
                } else {
                    // 没有打开相机的权限
                    Toast.makeText(this, "没有打开照相机权限", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    //选择视频
    private void selectVideo() {

        if (android.os.Build.BRAND.equals("Huawei")) {
            Intent intentPic = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intentPic, 2);
        }
        if (android.os.Build.BRAND.equals("Xiaomi")) {//是否是小米设备,是的话用到弹窗选取入口的方法去选取视频
            Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "video/*");
            startActivityForResult(Intent.createChooser(intent, "选择要导入的视频"), 2);
        } else {//直接跳到系统相册去选取视频
            Intent intent = new Intent();
            if (Build.VERSION.SDK_INT < 19) {
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.setType("video/*");
            } else {
                intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("video/*");
            }
            startActivityForResult(Intent.createChooser(intent, "选择要导入的视频"), 2);
        }

    }

    private OkHttpClient okHttpClient;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK && null != data) {
            String sdState = Environment.getExternalStorageState();
            if (!sdState.equals(Environment.MEDIA_MOUNTED)) {
                return;
            }
            String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
            Bundle bundle = data.getExtras();
            //获取相机返回的数据，并转换为图片格式
            Bitmap bitmap = (Bitmap) bundle.get("data");
            FileOutputStream fout = null;
            File file = new File("/sdcard/pics/");
            file.mkdirs();
            String filename = file.getPath() + name;
            try {
                fout = new FileOutputStream(filename);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fout);
                showImage(filename);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    fout.flush();
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //显示图片
        } else if (requestCode == IMAGE && resultCode == Activity.RESULT_OK && data != null) {
            //获取图片路径
            Uri selectedImage = data.getData();
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            String imagePath = c.getString(columnIndex);
            showImage(imagePath);
            c.close();
        } else if (resultCode == RESULT_OK && null != data && requestCode == 2) {
            videouri = data.getData();
            Cursor cursor = getContentResolver().query(videouri, null, null,
                    null, null);
            cursor.moveToFirst();
            // String imgNo = cursor.getString(0); // 图片编号
//            String v_name = cursor.getString(3); // 图片文件名
//            String path = cursor.getString(0); // 图片文件路径
            String size = cursor.getString(1); // 图片大小

            String path = UriUtils.getPath(AddextensionActivity.this, videouri);

            showProgressDialog();
//            progDialog.setMessage("正在压缩...");
            startCompressed(path);

        }
    }


    private void startCompressed(String videoPath) {
        if (isCompressing) {
            return;
        }
        isCompressing = true;
        //PLShortVideoTranscoder初始化，三个参数，第一个context，第二个要压缩文件的路径，第三个视频压缩后输出的路径
        PLShortVideoTranscoder mShortVideoTranscoder = new PLShortVideoTranscoder(this, videoPath, "/storage/emulated/0/DCIM/Camera/12.mp4");
        MediaMetadataRetriever retr = new MediaMetadataRetriever();
        retr.setDataSource(videoPath);
        String height = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); // 视频高度
        String width = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH); // 视频宽度
        String rotation = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION); // 视频旋转方向
        int transcodingBitrateLevel = 6;
        mShortVideoTranscoder.transcode(Integer.parseInt(width), Integer.parseInt(height), getEncodingBitrateLevel(transcodingBitrateLevel), false, new PLVideoSaveListener() {
            @Override
            public void onSaveVideoSuccess(String s) {
                handler.sendEmptyMessage(103);
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        LogUtil.e("onSaveVideoSuccess======== " + s);
//                    }
//                });
            }

            @Override
            public void onSaveVideoFailed(final int errorCode) {
                isCompressing = false;
                Log.e("snow", "save failed: " + errorCode);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (errorCode) {
                            case ERROR_NO_VIDEO_TRACK:
//                                ToastUtils.getInstance().showToast("该文件没有视频信息！");
                                break;
                            case ERROR_SRC_DST_SAME_FILE_PATH:
//                                ToastUtils.getInstance().showToast("源文件路径和目标路径不能相同！");
                                break;
                            case ERROR_LOW_MEMORY:
//                                ToastUtils.getInstance().showToast("手机内存不足，无法对该视频进行时光倒流！");
                                break;
                            default:
//                                ToastUtils.getInstance().showToast("transcode failed: " + errorCode);
                        }
                    }
                });
            }

            @Override
            public void onSaveVideoCanceled() {
                handler.sendEmptyMessage(101);
//                LogUtil.e("onSaveVideoCanceled");
            }

            @Override
            public void onProgressUpdate(float percentag) {
                handler.sendEmptyMessage(100);
//                LogUtil.e("onProgressUpdate==========" + percentage);
            }
        });
    }


    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 100:
                    break;
                case 101:
                    dissmissProgressDialog();
                    Toast.makeText(AddextensionActivity.this, "视频取消压缩", Toast.LENGTH_SHORT).show();
                    break;
                case 102:
                    break;
                case 103:
//                    progDialog.setMessage("正在上传...");
                    String compressedFilePath = "/storage/emulated/0/DCIM/Camera/12.mp4";
                    Log.i("压缩后", "压缩后视频大小:" + getFormatSize(getFileSize(new File(compressedFilePath))));
                    String formatSize = getFormatSize(getFileSize(new File(compressedFilePath)));
                    if (formatSize.equals("")) {
                        dissmissProgressDialog();
                    } else {
//                    getFormatSize(getFileSize(new File(compressedFilePath)))
                        String v_name = getFileName(compressedFilePath);
                        RequestBody requestBody = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM)
                                .addFormDataPart("video", v_name, RequestBody.create(MediaType.parse("image/jpg"), new File(compressedFilePath)))
                                .build();
                        Request request = new Request.Builder()
                                .url(Constant.PATH + Constant.add_video)
                                .post(requestBody)
                                .build();
                        okHttpClient.newCall(request).enqueue(callback_upload);
                    }
                    break;
                default:
            }
            return false;
        }
    });


    /**
     * 设置压缩质量
     *
     * @param position
     * @return
     */
    private int getEncodingBitrateLevel(int position) {
        return ENCODING_BITRATE_LEVEL_ARRAY[position];
    }

    /**
     * 选的越高文件质量越大，质量越好,对应压缩后尺寸更大
     */
    public static final int[] ENCODING_BITRATE_LEVEL_ARRAY = {
            500 * 1000,
            800 * 1000,
            1000 * 1000,
            1200 * 1000,
            1600 * 1000,
            2000 * 1000,
            2500 * 1000,
            4000 * 1000,
            8000 * 1000,
    };


    /**
     * 获取指定文件大小
     *
     * @return
     * @throws Exception
     */
    private static long getFileSize(File file) {
        long size = 0;
        try {
            if (file.exists()) {
                FileInputStream fis = null;
                fis = new FileInputStream(file);
                size = fis.available();
            } else {
                file.createNewFile();
                Log.e("获取文件大小", "文件不存在!");
            }
            return size;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 格式化单位
     *
     * @param size
     */

    public String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "MB";
        }
        double megaByte = kiloByte / 1024;
//        if (megaByte < 1) {
//
//            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
//            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
//        }
        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            if (megaByte > 100) {
                Toast.makeText(this, "文件过大，请重新选择", Toast.LENGTH_SHORT).show();
                return "";
            }
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }
        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }


    //上传请求后的回调方法
    private Callback callback_upload = new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            setResult(e.getMessage(), false);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            setResult(response.body().string(), true);
        }
    };
    final MediaPlayer[] mediaPlayer = new MediaPlayer[1];
    boolean isPlaying = true;

    //显示请求返回的结果
    private void setResult(final String msg, final boolean success) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (success) {
                    dissmissProgressDialog();
                    videoimage.setVisibility(View.GONE);
                    video_rela.setVisibility(View.VISIBLE);

                    AddVideoBean addVideoBean = new Gson().fromJson(msg, AddVideoBean.class);

                    videoView.setVideoURI(videouri);
                    videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                        }
                    });
                    videoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                        @Override
                        public boolean onInfo(MediaPlayer mp, int what, int extra) {
                            mediaPlayer[0] = mp;
                            mp.setLooping(true);
                            imgThumb.animate().alpha(0).setDuration(200).start();
                            return false;
                        }
                    });
                    love.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (videoView.isPlaying()) {
                                imgPlay.animate().alpha(0.7f).start();
                                videoView.pause();
                                isPlaying = false;
                            } else {
                                imgPlay.animate().alpha(0f).start();
                                videoView.start();
                                isPlaying = true;
                            }
                        }
                    });

                    videoView.start();

                    link = addVideoBean.getData();
                    Toast.makeText(AddextensionActivity.this, "视频上传成功", Toast.LENGTH_SHORT).show();
                } else {
                    dissmissProgressDialog();
                    Toast.makeText(AddextensionActivity.this, "视频上传失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public String getFileName(String pathandname) {

        int start = pathandname.lastIndexOf("/");
        //int end=pathandname.lastIndexOf("");
        if (start != -1) {
            return pathandname.substring(start + 1);
        } else {
            return null;
        }

    }


    String cover_pic = "";

    //加载图片
    private void showImage(String imaePath) {
        Bitmap bm = BitmapFactory.decodeFile(imaePath);
        String url = TakePhotoUtil.saveTodisk(bm, Constant.HeadPath);
        if (iswechat_card) {
            uploadImage(url);
            wechatCard.setImageBitmap(bm);
        } else {
            cover_pic = url;
            image.setImageBitmap(bm);
        }
    }

    public String bitmapToString(Bitmap bitmap) {
        //将bitmap转换为uri
        Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null, null));
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
        int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        actualimagecursor.moveToFirst();
        String img_path = actualimagecursor.getString(actual_image_column_index);
        return img_path;
    }


}
